#!/usr/bin/env node
/**
 * Phase3 RAG 面板匹配详情生成器
 * 用法：node scripts/phase3/generate-rag-match-details.js ComponentName
 *
 * 依据 phase2/preview-props-schema.json 与 panel-reuse-patterns-index.json
 */

const fs = require('fs');
const path = require('path');

function loadJson(filePath) {
  if (!fs.existsSync(filePath)) {
    throw new Error(`文件不存在: ${filePath}`);
  }
  return JSON.parse(fs.readFileSync(filePath, 'utf8'));
}

function inferPanel(fieldName, ragIndex) {
  const { matchingRules = {}, panelSummary = {} } = ragIndex;

  if (matchingRules[fieldName]) {
    return matchingRules[fieldName];
  }

  const entry = Object.entries(panelSummary).find(([, detail]) =>
    Array.isArray(detail.fields) && detail.fields.includes(fieldName)
  );

  return entry ? entry[0] : null;
}

function buildEntry(fieldName, panelName, ragIndex) {
  const panelSummary = ragIndex.panelSummary || {};
  const matchedPanel = panelName || 'unknown';
  const summary = panelSummary[matchedPanel];

  return {
    field: fieldName,
    matchedPanel,
    controlType: summary?.controlType || 'auto',
    belongTo: matchedPanel,
    confidence: matchedPanel === 'unknown' ? 0.4 : 0.92,
    ragSource: summary ? `panel-reuse-patterns-index.json#${matchedPanel}` : null
  };
}

function main() {
  const componentName = process.argv[2];
  if (!componentName) {
    console.error('用法: node scripts/phase3/generate-rag-match-details.js <ComponentName>');
    process.exit(1);
  }

  const root = process.cwd();
  const componentRoot = path.join(root, componentName);
  const schemaPath = path.join(componentRoot, 'phase2/preview-props-schema.json');
  const ragIndexPath = path.join(root, 'Workflow/FigmaMCPWorkflow/Resources/knowledge-base/panel-reuse-patterns-index.json');
  const outputPath = path.join(componentRoot, 'phase3/rag-match-details.json');

  try {
    console.log(`\n📚 生成 RAG 面板匹配详情: ${componentName}`);

    const schema = loadJson(schemaPath);
    const ragIndex = loadJson(ragIndexPath);
    const props = schema.propsInterface || schema.props || {};

    const entries = Object.keys(props).map(fieldName => {
      const matchedPanel = inferPanel(fieldName, ragIndex);
      return buildEntry(fieldName, matchedPanel, ragIndex);
    });

    const report = {
      component: componentName,
      timestamp: new Date().toISOString(),
      totalFields: entries.length,
      matched: entries.filter(e => e.matchedPanel !== 'unknown').length,
      entries
    };

    fs.mkdirSync(path.dirname(outputPath), { recursive: true });
    fs.writeFileSync(outputPath, JSON.stringify(report, null, 2));

    console.log(`  ✅ 写入 ${outputPath}`);
  } catch (error) {
    console.error(`❌ 生成失败: ${error.message}`);
    process.exit(1);
  }
}

main();
